package com.kotlin.library.rxbus;

import rx.Observable;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subjects.Subject;

/**
 * Created by binghu on 16-6-28.
 * used as eventbus
 */
public class RxBus {
    //private static final RxBus INSTANCE = new RxBus();
    //private Subject<Object, Object> busSubject =
    //        new SerializedSubject<>(PublishSubject.create());
    //
    //private RxBus() {
    //}
    //
    //public static RxBus getDefault() {
    //   return INSTANCE;
    //}
    //
    //public <T> Observable<T> register(Class<T> eventClass) {
    //    return busSubject.ofType(eventClass);
    //}
    //
    //public void post(Object event) {
    //    busSubject.onNext(event);
    //}
//-------------------------------------------------------------------------------
    private static volatile RxBus mInstance;
    private final Subject<Object, Object> bus;

    private RxBus() {
        bus = new SerializedSubject<>(PublishSubject.create());
    }


    public <T> Observable<T> register(Class<T> eventClass) {
        return bus.ofType(eventClass);
    }
    /**
     * 单例RxBus
     *
     * @return
     */
    public static RxBus getDefault() {
        RxBus rxBus = mInstance;
        if (mInstance == null) {
            synchronized (RxBus.class) {
                rxBus = mInstance;
                if (mInstance == null) {
                    rxBus = new RxBus();
                    mInstance = rxBus;
                }
            }
        }
        return rxBus;
    }

    /**
     * 发送一个新事件
     *
     * @param o
     */
    public void post(Object o) {
        bus.onNext(o);
    }

    /**
     * 返回特定类型的被观察者
     *
     * @param eventType
     * @param <T>
     * @return
     */
    //public <T> Observable<T> toObservable(Class<T> eventType) {
    //    return bus.ofType(eventType);
    //}


}
